import React,{Component} from 'react';
import {Prompt} from "react-router-dom";
export default class UserAdd extends Component{
    constructor (props) {
        super(props);
        this.state = {
            blockimg : false,  //是否组织跳转  默认不阻止
        }
    }
    //点击提交按钮时
    handleSubmit = () =>{
        let name = this.name.value;
        console.log(name);
        // 从缓存中获取用户列表的字符串  null 字符串
        let userStr = localStorage.getItem('users');
        let users = userStr?JSON.parse(userStr):[];
        //添加字符串对象
        users.push({id:Date.now(),name});
        //存到缓存
        localStorage.setItem('users',JSON.stringify(users));
        //把离开本页面的提示关掉
        this.setState({
            blockimg:false
        },()=>{
            //跳转到用户列表
            this.props.history.push('/user/list');
        });
    }
    //input 改变的时候
    handleChange = (event) => {
        let value = event.target.value;
        this.setState({
            blockimg:value&&value.length>1?true:false
        });
    }
    render(){
        return (
            <div>
                <Prompt
                    when = {this.state.blockimg}
                    message = { (location) => {
                        return `你确定要离开本页面${location.pathname}`;
                    }}
                />
                <form onSubmit={this.handleSubmit}>
                    <div className="input-group">
                        <input type="text" className="form-control" placeholder="请输入用户姓名" onChange={this.handleChange} ref={ref=>this.name=ref}  />
                        <span className="input-group-btn">
                            <button className="btn btn-primary"  type="submit">添加</button>
                        </span>
                    </div>
                </form>
            </div>
        )
    }
};